//Powered By SirYuxuan team MakeCode 
//www.yuxuan66.com
package com.systemsetup.systemsetup.web.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.systemsetup.systemsetup.common.base.BaseService;
import com.systemsetup.systemsetup.common.utils.Dict;
import com.systemsetup.systemsetup.common.utils.PasswordUtil;
import com.systemsetup.systemsetup.common.utils.cache.RedisUtil;
import com.systemsetup.systemsetup.common.utils.jwtUtils;
import com.systemsetup.systemsetup.model.*;
import com.systemsetup.systemsetup.support.model.RespEntity;
import com.systemsetup.systemsetup.support.mybatisplus.QueryWrapper;
import com.systemsetup.systemsetup.support.utils.requestutil.HttpRequestUtil;
import com.systemsetup.systemsetup.web.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class UserService extends BaseService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private UserPermissionMapper userPermissionMapper;
    @Resource
    private OrganizationMapper organizationMapper;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private TokenMapper tokenMapper;
    @Resource
    private AppUserCidMapper appUserCidMapper;
    @Resource
    private WeChatMapper weChatMapper;
    @Resource
    private PermissionsMapper permissionsMapper;
    @Resource
    private OrganizationTreeListService organizationTreeListService;
    @Resource
    private RolepermissionMapper rolepermissionMapper;
    @Resource
    private UserPermissionMapper userpermissionMapper;
    @Resource
    private BusinessMapper businessMapper;
    @Resource
    private ToppedApplicationInfoMapper toppedApplicationInfoMapper;

    private static final Logger logger = LoggerFactory.getLogger(UserService.class);


    /**
     * 账号删除
     *
     * @param jsonParam
     * @return
     */
    public RespEntity userDelete(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        String user_id = token.getString("user_id");
        String userId = jsonParam.getStr("id");
        if (StrUtil.isBlank(userId)) {
            return RespEntity.fail("Id为空");
        }
        if (user_id.equals(userId)) {
            return RespEntity.fail("无权限删除本账号!");
        }
        //删除用户绑定角色表
//        userRoleMapper.delete(new QueryWrapper<Userrole>().eq("user_id", userId));
        //删除用户表
        userMapper.deleteById(userId);
        userPermissionMapper.delete(new QueryWrapper<Userpermission>().eq("user_id", userId));
        //删除账号绑定置顶应用信息
        toppedApplicationInfoMapper.delete(new QueryWrapper<ToppedApplicationInfo>().eq("user_id",userId));
        //删除无忧舆情账号
        accountContactDeleteSub(userId);
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 删除无忧舆情账号
     * @Date Created in 9:58 2023/4/20
     * @Param [userId]
     */

    public void accountContactDeleteSub(String userId) {
        //参数
        cn.hutool.core.lang.Dict dict = new cn.hutool.core.lang.Dict();
        dict.set("userId", userId);
        dict.set("adminId", "szkjsd01");
        dict.set("platform", "EXAMPLE");
        try {
            JSONObject jsonObject = getRest(dict, "wuyouyuqing", "accountContactDeleteSub", "yuqing");
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }

    /**
     * @return com.systemsetup.systemsetup.support.model.RespEntity
     * @Author LiHaoDong
     * @Description 登录
     * @Date 16:25 2020/7/24
     * @Param [jsonParam]
     **/
    public RespEntity login(Dict dict) throws Exception {
        logger.info("loginDATA+++++++++" + dict.toString());
        String accountname = dict.getStr("accountname");
        String accountpassword = dict.getStr("accountpassword");
        String cid = dict.getStr("cid");
        //String passwordHash = PasswordUtil.createHash(accountpassword);
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("accountname", accountname);
        User user = this.userMapper.selectOne(queryWrapper);
        if (user == null) {
            return RespEntity.fail("用户不存在!");
        }
        if (user.getIsUse() == 2) {
            return RespEntity.fail("服务已到期请及时续费，谢谢合作!");
        }
        //导航栏权限
        List<String> navBar = permissionsMapper.navBarList(user.getRoleId());
        if (user.getType() == 1) {
            if (navBar.contains("028") || navBar.contains("029")) {
                navBar.remove("028");
                navBar.remove("029");
            }
        } else {
            if (navBar.contains("002") || navBar.contains("003") || navBar.contains("030")) {
                navBar.remove("002");
                navBar.remove("003");
                navBar.remove("030");
            }
        }
        //按钮权限
        List<String> buttonList = permissionsMapper.buttonList(user.getRoleId());
        String refresh_token = null;
        String access_token = null;
        if (user != null && !user.isEmpty()) {
            if (PasswordUtil.validatePassword(accountpassword, user.getAccountpassword())) {

                //组装最终数据
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("accountname", accountname);
                resultMap.put("userRealName", user.getName());
                resultMap.put("userType", user.getType());
                resultMap.put("homeId", user.getHomeId());
                resultMap.put("navBar", navBar);
                resultMap.put("buttonList", buttonList);
                resultMap.put("userId", user.getId());
                if (user.getType() == 1) {//为机构，赋值机构名称
                    Organization organization = this.organizationMapper.selectById(user.getHomeId());
                    resultMap.put("homeName", organization.getName());
                    if (organization.getId().equals("0")) {
                        user.put("reginid", organization.getReginid());
                    } else {
                        String allId = organization.getAllId();
                        String oneId = allId.split(",")[0];
                        Organization organizationOne = this.organizationMapper.selectById(oneId);
                        user.put("reginid", organizationOne.getReginid());
                    }
                    resultMap.put("reginId", organization.getReginid());
                    resultMap.put("orgId", user.getHomeId());
                } else {//为单位
                    //rest请求单位详情接口，获取单位信息，赋值单位名称
                    JSONObject jsonParamN = new JSONObject();
                    String homeId = user.getHomeId();
                    jsonParamN.put("id", user.getHomeId());
                    com.alibaba.fastjson.JSONObject businessDetail = makeData(jsonParamN, "businessJava", "config", "getBusinessDetailNoToken", "business");
                    if (StrUtil.isNotBlank(businessDetail.getString("methodErrorFlag")))
                        return RespEntity.fail(businessDetail.getString("msg"));
                    String name = businessDetail.getString("name");
                    resultMap.put("homeName", name);
                    resultMap.put("orgId", businessDetail.getString("orgId"));
                }
                resultMap.put("exhibitionType", user.getExhibitionType());
                //生成长短token
                refresh_token = jwtUtils.createLongtToken(user);
                access_token = jwtUtils.createShortToken(user);
                resultMap.put("token", access_token);
                resultMap.put("refresh_token", refresh_token);
                insertToken(refresh_token, access_token);
                insertToken(access_token, "1");
//                redisUtil.set(refresh_token,access_token);
//                redisUtil.set(access_token,"1");
                if (dict.containsKey("cid")) {
                    //对cid操作
                    AppUserCid appUserCid = new AppUserCid();
                    appUserCid.setCid(cid);
                    appUserCid.setId(user.getId());
                    appUserCid.setAccountname(user.getAccountname());
                    int count = appUserCidMapper.selectCount(new QueryWrapper<AppUserCid>().eq("id", user.getId()).eq("cid", cid));
                    if (count == 0 && cid != null && StrUtil.isNotBlank(cid)) {
                        appUserCidMapper.insert(appUserCid);
                    }
                    logger.info("++++++++app+++++++++:" + dict.toString());
                }
                if ("app".equals(dict.getStr("source"))) {
                    //登录的时候先删除原来的openid
                    if (dict.getStr("openid") != null && StrUtil.isNotBlank(dict.getStr("openid"))) {
                        weChatMapper.delete(new QueryWrapper<WeChat>().eq("open_id", dict.getStr("openid")));
                    }
                    // openid要存到数据库对应单位用户
                    WeChat weChat = new WeChat();
                    weChat.setId(UUID.randomUUID().toString());
                    weChat.setUserId(user.getId());
                    weChat.setOpenId(dict.getStr("openid"));
                    weChatMapper.insert(weChat);
                }
                return RespEntity.success(resultMap);
            }
            return RespEntity.fail("密码错误");
        }
        return RespEntity.fail("用户名不存在");
    }

    /**
     * @Author YangYu
     * @Description 用户注册
     * @Date Created in 14:08 2024/5/7
     * @Param [jsonParam]
     */

    public RespEntity register(JSONObject jsonParam) throws ParseException {
        String name = "";
        //校验手机号或验证码是否为空
        if (StrUtil.isBlank(jsonParam.getStr("phone")) || StrUtil.isBlank(jsonParam.getStr("code"))) {
            return RespEntity.fail("手机号或验证码不能为空!");
        }
        //校验用户是否存在
        int userCount = userMapper.selectCount(new QueryWrapper<User>().eq("accountname", jsonParam.getStr("phone")));
        if (userCount > 0) {
            return RespEntity.fail("用户名已存在,请登录!");
        }
        //校验验证码是否存在
        if (!redisUtil.exists(jsonParam.getStr("phone"))) {
            return RespEntity.fail("验证码错误或已失效!");
        }
        //校验验证码是否在有效时间内
        Map<String, Object> jsonObject = (Map<String, Object>) redisUtil.get(jsonParam.getStr("phone"));
        if (getNMinute(jsonObject.get("time").toString())) {
            return RespEntity.fail("验证码错误或已失效!");
        }
        //校验验证码数据是否和系统一致
        if (!jsonObject.get("code").toString().equals(jsonParam.getStr("code"))) {
            return RespEntity.fail("验证码错误或已失效!");
        }
        redisUtil.remove(jsonParam.getStr("phone"));
        User user = new User();
        // type 1运营单位 2业主单位 3施工单位
        if (jsonParam.getInt("type") == 1) {
            name = jsonParam.getStr("name");
            int count = organizationMapper.selectCount(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Organization>().eq("name", name));
            if (count > 0) {
                return RespEntity.fail("该名称已被注册,详情请联系管理员!");
            }
            //新增机构
            String id = UUID.randomUUID().toString();
            Organization organization = new Organization();
            organization.setName(name);
            String pid = "001e7548-8735-4b31-b30b-c9361a62c102";
            if (StrUtil.isNotBlank(jsonParam.getStr("invitationCode"))) {
                pid = jsonParam.getStr("invitationCode");
            }
            organization.setPid(pid);
            organization.setId(id);
            if (pid.equals("0")) {
                organization.setAllId(id);
            } else {
                String orgIds = organizationTreeListService.getOrganizationss("", pid);
                organization.setAllId(orgIds + "," + id);
            }
            organizationMapper.insert(organization);
            user.setHomeId(id);
            user.setRoleId("95eafbbf-453c-4533-be7b-2537a5c9e20b");
        } else if (jsonParam.getInt("type") == 2) {
            name = jsonParam.getStr("name");
            int count = businessMapper.selectCount(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Business>().eq("name", name));
            if (count > 0) {
                return RespEntity.fail("该名称已被注册,详情请联系管理员!");
            }
            user.setRoleId("09ab3104-5008-4c2d-ad8c-f2b4caa1c9a6");
        }else if (jsonParam.getInt("type") == 3) {

        }
        String departmentId = "";
        if (jsonParam.getInt("type") != 1) {
            departmentId = "0";
        }

        user.setId(UUID.randomUUID().toString());
        user.setAccountname(jsonParam.getStr("phone"));
        user.setAccountpassword(PasswordUtil.createHash(jsonParam.getStr("accountPassword")));
        user.setName(name);
        user.setIsUse(1);
        user.setPhone(jsonParam.getStr("phone"));
        user.setDepartmentId(departmentId);
        user.setCreatetime(new Date());
        user.setType(jsonParam.getInt("type"));
        //修改user数据库
        userMapper.insert(user);
        List<Rolepermission> rolepermissionList = rolepermissionMapper.selectList(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Rolepermission>().eq("role_id", user.getRoleId()));
        List<Userpermission> list = new ArrayList<>();
        for (Rolepermission rolepermission : rolepermissionList) {
            //权限设置
            Userpermission userpermission = new Userpermission();
            userpermission.setUserId(user.getId());
            userpermission.setPermissionId(rolepermission.getPermissionId());
            userpermission.setCreatetime(user.getCreatetime());
            list.add(userpermission);
        }
        userpermissionMapper.insertZB(list);
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 更新用户绑定单位
     * @Date Created in 13:47 2024/5/8
     * @Param [jsonParam]
     */

    public RespEntity updateUserHomeId(JSONObject jsonParam){
        if (StrUtil.isBlank(jsonParam.getStr("userId")) || StrUtil.isBlank(jsonParam.getStr("businessId"))){
            return RespEntity.fail("userId或businessId不能为空!");
        }
        User user = new User();
        user.setId(jsonParam.getStr("userId"));
        user.setHomeId(jsonParam.getStr("businessId"));
        userMapper.updateById(user);
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 获取验证码（找回密码用）
     * @Date Created in 13:47 2024/5/8
     * @Param [jsonParam]
     */

    public RespEntity getVerificationCode(JSONObject jsonParam){
        if (StrUtil.isBlank(jsonParam.getStr("phone"))){
            return RespEntity.fail("phone不能为空!该手机号未注册账号！");
        }
        //校验账号是否存在
        int count = userMapper.selectCount(new QueryWrapper<User>().eq("accountname",jsonParam.getStr("phone")));
        if (count == 0){
            return RespEntity.fail("该手机号未注册账号!");
        }
        return restPostOrGet(jsonParam,"communicationJava","register","communication","POST");
    }

    /**
     * @Author YangYu
     * @Description 身份验证（找回密码用）
     * @Date Created in 13:47 2024/5/8
     * @Param [jsonParam]
     */

    public RespEntity identityVerification(JSONObject jsonParam) throws ParseException {
        //校验手机号或验证码是否为空
        if (StrUtil.isBlank(jsonParam.getStr("phone")) || StrUtil.isBlank(jsonParam.getStr("code"))) {
            return RespEntity.fail("手机号或验证码不能为空!");
        }
        //校验验证码是否存在
        if (!redisUtil.exists(jsonParam.getStr("phone"))) {
            return RespEntity.fail("验证码错误或已失效!");
        }
        //校验验证码是否在有效时间内
        Map<String, Object> jsonObject = (Map<String, Object>) redisUtil.get(jsonParam.getStr("phone"));
        if (getNMinute(jsonObject.get("time").toString())) {
            return RespEntity.fail("验证码错误或已失效!");
        }
        //校验验证码数据是否和系统一致
        if (!jsonObject.get("code").toString().equals(jsonParam.getStr("code"))) {
            return RespEntity.fail("验证码错误或已失效!");
        }
        redisUtil.remove(jsonParam.getStr("phone"));
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 密码重置（忘记密码用）
     * @Date Created in 17:11 2024/5/10
     * @Param [jsonParam]
     */

    public RespEntity passwordReset(JSONObject jsonParam){
        //校验手机号或密码是否为空
        if (StrUtil.isBlank(jsonParam.getStr("phone")) || StrUtil.isBlank(jsonParam.getStr("password"))) {
            return RespEntity.fail("手机号或密码不能为空!");
        }
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("accountname",jsonParam.getStr("phone")));
        user.setAccountpassword(PasswordUtil.createHash(jsonParam.getStr("password")));
        userMapper.updateById(user);
        return RespEntity.success("密码修改成功!");
    }
    /**
     * @Author YangYu
     * @Description 校验验证码时间是否失效（3分钟内有效）
     * @Date Created in 10:11 2024/5/8
     * @Param [oldDateStr]
     */

    public boolean getNMinute(String oldDateStr) throws ParseException {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        int minute = calendar.get(Calendar.MINUTE);
        calendar.set(Calendar.MINUTE, minute - 3);
        Date newDate = new Date(calendar.getTimeInMillis());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date oldDate = simpleDateFormat.parse(oldDateStr);
        return newDate.getTime() >= oldDate.getTime();
    }

    //退出短token
    public RespEntity logout(Dict dict, HttpServletRequest httpServletRequest, HttpServletResponse response) {

        String authorization = httpServletRequest.getHeader("Authorization");
//        boolean flag = redisUtil.exists(authorization.split(" ")[1]);
        boolean flag = existsToken(authorization.split(" ")[1]);
        //验证短token
        if (flag) {//说明缓存存在这个token
            try {
                jwtUtils.verifyShortToken(authorization.split(" ")[1]);
            } catch (UnsupportedEncodingException UnsupportedEncodingException) {
                return RespEntity.fail("加密失效");
            } catch (TokenExpiredException TokenExpiredException) {
                response.setStatus(401);
                return RespEntity.expire();
            }
//            redisUtil.remove(authorization.split(" ")[1]);
            deleteToken(authorization.split(" ")[1]);
        } else {
            response.setStatus(401);
            return RespEntity.expire();
        }
        return RespEntity.success("成功退出短token");
    }

    //退出长token
    public RespEntity logout2(JSONObject jsonparm, HttpServletRequest httpServletRequest, HttpServletResponse response) {
        jsonparm = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        String authorization = httpServletRequest.getHeader("Authorization");
//        boolean flag = redisUtil.exists(authorization.split(" ")[1]);
        boolean flag = existsToken(authorization.split(" ")[1]);
        //验证长token
        if (flag) {//说明缓存存在这个token
            try {
                jwtUtils.verifyLongToken(authorization.split(" ")[1]);
                //删除openid相关数据
                logger.info("+++++++++dropoutToken+++++" + jsonparm.toString());
                if (jsonparm.getStr("openid") != null && StrUtil.isNotBlank(jsonparm.getStr("openid"))) {
                    weChatMapper.delete(new QueryWrapper<WeChat>().eq("open_id", jsonparm.getStr("openid")));
                }
                //删除cid相关数据
                if (jsonparm.getStr("cid") != null && StrUtil.isNotBlank(jsonparm.getStr("cid"))) {
                    appUserCidMapper.delete(new QueryWrapper<AppUserCid>().eq("cid", jsonparm.getStr("cid")));
                }
            } catch (UnsupportedEncodingException UnsupportedEncodingException) {
                return RespEntity.fail("加密失效");
            } catch (TokenExpiredException TokenExpiredException) {
                response.setStatus(401);
                return RespEntity.expire();
            }
//            redisUtil.remove(authorization.split(" ")[1]);
            deleteToken(authorization.split(" ")[1]);
        } else {
            response.setStatus(401);
            return RespEntity.expire();
        }
        return RespEntity.success("成功退出长token");
    }

    //刷新数据
    public RespEntity refresh(Dict dict, HttpServletRequest httpServletRequest, HttpServletResponse response) {
        //验证长token是否过期
        DecodedJWT jwt = null;
        String authorization = httpServletRequest.getHeader("Authorization");
//        boolean flag = redisUtil.exists(authorization.split(" ")[1]);
        boolean flag = existsToken(authorization.split(" ")[1]);
        //验证长token
        if (flag) {//说明缓存存在这个token
            try {
                jwt = jwtUtils.verifyLongToken(authorization.split(" ")[1]);
            } catch (TokenExpiredException | UnsupportedEncodingException e) {
                deleteToken(authorization.split(" ")[1]);
                response.setStatus(401);
                return RespEntity.expire();
            }
            //解析数据
            User analysis = analysis(httpServletRequest, jwt);
            if (analysis.getIsUse() == 2) {
                deleteToken(authorization.split(" ")[1]);
                response.setStatus(401);
                return RespEntity.expire();
            }
            //生成新的短token
            String shortToken = null;
            try {
                shortToken = jwtUtils.createShortToken(analysis);
                //删除原来的短token
//                redisUtil.remove(redisUtil.get(authorization.split(" ")[1]).toString());
                deleteToken(getToken(authorization.split(" ")[1]));
                deleteToken(authorization.split(" ")[1]);
                insertToken(authorization.split(" ")[1], shortToken);
                insertToken(shortToken, "1");
//                redisUtil.set(authorization.split(" ")[1],shortToken);
//                redisUtil.set(shortToken,"1");
            } catch (UnsupportedEncodingException e) {
                return RespEntity.fail("加密失效");
            }
            Map<String, Object> map = new HashMap<>();
            map.put("token", shortToken);
            return RespEntity.success(map);
        } else {
            response.setStatus(401);
            return RespEntity.expire();
        }
    }

    //解析一下数据
    public User analysis(HttpServletRequest httpServletRequest, DecodedJWT jwt) {

        //获取数据
        Map<String, Claim> claims = jwt.getClaims();
        for (Map.Entry<String, Claim> entry : claims.entrySet()) {
            String key = entry.getKey();
            Claim claim = entry.getValue();
        }
        String id = claims.get("id").asString();
        String homeid = "";
        if (claims.containsKey("home_id")){
            homeid =  claims.get("home_id").asString();
        }
        Integer type = claims.get("type").asInt();
        User user = new User();
        if (claims.containsKey("reginid")) {
            String reginid = claims.get("reginid").asString();
            user.put("reginid", reginid);
        }
        User isUse = userMapper.selectById(id);
        if (isUse == null) {
            user.setIsUse(2);
        } else {
            user.setIsUse(isUse.getIsUse());
        }
        user.setId(id);
        user.setHomeId(homeid);
        user.setType(type);
        return user;
    }

    //解析token
    public RespEntity getDecodeToken(Dict dict, HttpServletRequest httpServletRequest, HttpServletResponse response) {
        //验证短token是否过期
        DecodedJWT jwt = null;
        String authorization = httpServletRequest.getHeader("Authorization");
//        boolean flag = redisUtil.exists(authorization.split(" ")[1]);
        if (StrUtil.isBlank(authorization)) {
            response.setStatus(401);
            return RespEntity.expire();
        }
        boolean flag = existsToken(authorization.split(" ")[1]);
        //验证长token
        if (flag) {//说明缓存存在这个token
            try {
                jwt = jwtUtils.verifyShortToken(authorization.split(" ")[1]);
                //解析数据
                User analysis = analysis(httpServletRequest, jwt);
                if (analysis.getIsUse() == 2) {
                    deleteToken(authorization.split(" ")[1]);
                    response.setStatus(401);
                    return RespEntity.expire();
                }
                Map<String, Object> map = new HashMap<>();
                map.put("home_id", analysis.getHomeId());
                map.put("user_type", analysis.getType());
                map.put("user_id", analysis.getId());
                map.put("reginid", analysis.getString("reginid"));
                return RespEntity.success(map);
            } catch (TokenExpiredException | UnsupportedEncodingException e) {
                deleteToken(authorization.split(" ")[1]);
                response.setStatus(401);
                return RespEntity.expire();
            }
        } else {
            response.setStatus(401);
            return RespEntity.expire();
        }
    }

    /**
     * @Author YangYu
     * @Description 通过传参解析token
     * @Date Created in 15:06 2024/6/5
     * @Param [dict, httpServletRequest, response]
     */

    public RespEntity getDecodeTokenNew(JSONObject jsonParam, HttpServletRequest httpServletRequest, HttpServletResponse response) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //验证短token是否过期
        DecodedJWT jwt = null;
        String authorization = jsonParam.getStr("token");
//        boolean flag = redisUtil.exists(authorization.split(" ")[1]);
        if (StrUtil.isBlank(authorization)) {
            response.setStatus(401);
            return RespEntity.expire();
        }
        boolean flag = existsToken(authorization);
        //验证长token
        if (flag) {//说明缓存存在这个token
            try {
                jwt = jwtUtils.verifyShortToken(authorization);
                //解析数据
                User analysis = analysis(httpServletRequest, jwt);
                if (analysis.getIsUse() == 2) {
                    deleteToken(authorization);
                    response.setStatus(401);
                    return RespEntity.expire();
                }
                Map<String, Object> map = new HashMap<>();
                map.put("home_id", analysis.getHomeId());
                map.put("user_type", analysis.getType());
                map.put("user_id", analysis.getId());
                map.put("reginid", analysis.getString("reginid"));
                return RespEntity.success(map);
            } catch (TokenExpiredException | UnsupportedEncodingException e) {
                deleteToken(authorization);
                response.setStatus(401);
                return RespEntity.expire();
            }
        } else {
            response.setStatus(401);
            return RespEntity.expire();
        }
    }
    public RespEntity userListByOrgId(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        List<User> users = this.userMapper.userListByOrgId(jsonParam);
        return RespEntity.success(users);
    }

    public void insertToken(String key, String value) {
        Token token = new Token();
        token.setKeys(key);
        token.setValues(value);
        tokenMapper.insertToken(token);
    }

    public void deleteToken(String key) {
        tokenMapper.deleteToken(key);
    }

    public boolean existsToken(String key) {
        int count = tokenMapper.existsToken(key);
        if (count > 0) {
            return true;
        }
        return false;
    }

    public String getToken(String key) {
        List<Token> list = tokenMapper.getToken(key);
        if (!list.isEmpty()) {
            return list.get(0).getValues();
        }
        return null;
    }

}
